const fs = require("fs");
const path = require("path");

// 项目根目录绝对路径
const rootDir = path.resolve(__dirname, "../");
// 要读取的文件夹和文件名
const folder = "catchData";

function loadCache(file) {
  try {
    const filePath = path.join(rootDir, folder, file);
    const data = fs.readFileSync(filePath);
    return JSON.parse(data);
  } catch (error) {
    return {};
  }
}

function saveCache(file, cache) {
  const filePath = path.join(rootDir, folder, file);
  fs.writeFileSync(filePath, JSON.stringify(cache));
}

function getCache(file, key) {
  const cache = loadCache(file);
  const item = cache[key];

  if (item && item.expiresAt && item.expiresAt < Date.now()) {
    deleteCache(key);
    return undefined;
  }

  return item ? JSON.parse(item.value) : undefined;
}

function getAllCatch(file) {
  const cache = loadCache(file);
  const keys = Object.keys(cache);
  return keys.map((item) => JSON.parse(cache[item].value)) || [];
}

function setCache(file, key, value, expiresInSeconds) {
  const cache = loadCache(file);
  if (expiresInSeconds) {
    const expiresAt = Date.now() + expiresInSeconds * 1000;
    cache[key] = { value: JSON.stringify(value), expiresAt };
  } else {
    cache[key] = { value: JSON.stringify(value) };
  }

  saveCache(file, cache);
}

function deleteCache(file, key) {
  const cache = loadCache(file);
  delete cache[key];
  saveCache(file, cache);
}

// 使用示例
/* const user = { name: 'John', age: 30, email: 'john@example.com' };
setCache('xxx.json','user', user, 10); // 设置过期时间为10秒
console.log(getCache('user')); // 输出: { name: 'John', age: 30, email: 'john@example.com' }

setTimeout(() => {
  console.log(getCache('xxx.json','user')); // 输出: undefined，因为缓存已过期
}, 11000); */

module.exports = {
  setCache,
  deleteCache,
  getCache,
  getAllCatch
};
